#pragma once

#include "log.hpp"
#include "protocol.hpp"
#include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <functional>

using namespace std;

namespace server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    static const uint16_t gport = 8080;
    static const int gbacklog = 5;

    typedef std::function<void(const Request &req, Response &resp)> func_t;


    // 保证解耦
    void HandlerEntery(int sock, func_t func)
    {
        std::string inbuffer;
        while (true)
        {
            // 读取
            // 怎么确定保证读到的是一个完整的请求
            std::string req_text, req_str;
            if (!recvPackage(sock, inbuffer, &req_text))
                return;
            std::cout<<"带报头的请求: \n"<<req_text<<std::endl;
            // 到这里，保证我们的req_text里面一定是一个完整的请求"content_len"\r\n"x op y"\r\n
            if (!deLength(req_text, &req_str))
                return;
            std::cout<<"去掉报头的正文: \n"<<req_str<<std::endl;

            // 对请求Request,反序列化
            // 得到一个结构化的请求对象

            Request req;
            if (!req.deserialize(req_str))
                return;
            //std::cout<<req.x<<" "<<req.y<<" "<<req.op<<std::endl;
            // 计算业务处理，req.x,req.op,req.y
            // 得到一个结构化响应
            Response resp;
            //std::cout<<resp.result<<std::endl;
            func(req, resp);
            //std::cout<<resp.result<<std::endl;
            // 对相应Response,进行序列化
            // 得到一个'字符串'
            std::string resp_str;
            resp.serialize(&resp_str);

            std::cout<<"计算完成，序列化响应: "<<resp_str<<std::endl;

            // 然后我们再发送响应
            // 构建一个完整的报文
            std::string send_string = enLength(resp_str);

            std::cout<<"构建完成完整的响应\n"<<send_string<<std::endl;

            send(sock, send_string.c_str(), send_string.size(), 0);
        }
    }

    class CalServer
    {
    public:
        CalServer(const uint16_t &port = gport) : _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // 创建socket套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "creat socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "creat socket success: %d",_listensock);

            // 绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success");
            // 设置socket 为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success");
        }
        void start(func_t func)
        {

            for (;;)
            {
                // signal (SIGCHLD,SIG_IGN);多进程信号忽略版
                //  获取新链接
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error,next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success,get a new sock:%d", sock);

                // verson 2 多进程版
                pid_t id = fork();
                if (id == 0) // child
                {
                    close(_listensock);
                    // if(fork()>0) exit(0);
                    // serviceIO(sock);
                    HandlerEntery(sock, func);
                    close(sock);
                    exit(0);
                }
                // father
                pid_t ret = waitpid(id, nullptr, 0);
                if (ret > 0)
                {
                    logMessage(NORMAL, "wait child success");
                }
            }
        }

        ~CalServer()
        {
        }

    private:
        int _listensock; // 不用来数据通信，用来监听，获取新链接
        uint16_t _port;
    };
}